﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;
using Revis.VClinicNet.Core.Domain.Credentials;
using Revis.VClinicNet.Core.Domain.Repository;

namespace Revis.VClinicNet.Core.Domain.Persistence.Nh
{
    public class PatientUserRepository : RepositoryBase<PatientUser>, IPatientUserRepository
    {
        public PatientUserRepository(ISessionFactory factory)
            : base(factory)
        {
        }

        public PatientUser Find(string login, string password)
        {
            return Session.CreateCriteria<PatientUser>()
                .CreateAlias("Related", "Patient")
                .Add(Expression.Eq("Patient.Personal.Pesel", login))
                .Add(Expression.Eq("Password", password))
                .UniqueResult<PatientUser>();
        }

        public PatientUser Find(string login)
        {
            return Session.CreateCriteria<PatientUser>("pu")
                .Add(Expression.Eq("pu.Related.Personal.Pesel", login))
                .UniqueResult<PatientUser>();
        }

        public override IList<PatientUser> FindBy(string field, string value)
        {
            IList<PatientUser> finded = null;
            try {
                finded = Session.CreateCriteria<PatientUser>()
                    .CreateAlias("Related", "Patient")
                    .Add(Expression.Like(field, value, MatchMode.Anywhere)).List<PatientUser>();
            } catch (QueryException) {
                finded = null;
            }
            return finded;
        }


        public PatientUser FindByPatientId(long patientId)
        {
            return Session.CreateCriteria<PatientUser>("pu")
                .Add(Expression.Eq("pu.Related.Id", patientId))
                .UniqueResult<PatientUser>();
        }


        public PatientUser FindByPatientPesel(string pesel)
        {
            return Session.CreateCriteria<PatientUser>()
                .CreateAlias("Related", "Patient")
                .Add(Expression.Eq("Patient.Personal.Pesel", pesel))
                .UniqueResult<PatientUser>();
        }
    }
}
